const localVideo = document.getElementById("localVideo")
const remoteVideo = document.getElementById("remoteVideo")

const startBtn = document.getElementById("startBtn")
const callBtn = document.getElementById("callBtn")
const hangupBtn = document.getElementById("hangupBtn")

let pc1
let pc2
let localStream

function start() {
    const options = {
        video: true,
        audio: false
    }
    navigator.mediaDevices.getUserMedia(options).then(stream => {
        localVideo.srcObject = stream
        localStream = stream
    }).catch(err => {
        console.error(err)
    })
}



function handleError(e) {
    console.error(e)
} 

function call() {
    pc1 = new RTCPeerConnection()
    pc2 = new RTCPeerConnection()


    pc1.onicecandidate = e => {
        if(!e.candidate) return
        pc2.addIceCandidate(e.candidate)
            .catch(handleError);
        console.log('pc1 ICE candidate:', e.candidate);
    }
    pc2.onicecandidate = e => {
        if(!e.candidate) return
        pc1.addIceCandidate(e.candidate)
            .catch(handleError);
        console.log('pc2 ICE candidate:', e.candidate);
    }

    pc2.ontrack = (e) => {
        console.log(e)
        if(remoteVideo.srcObject !== e.streams[0]){
            remoteVideo.srcObject = e.streams[0];
        }
    }

	//add Stream to caller
	localStream.getTracks().forEach((track)=>{
		pc1.addTrack(track, localStream);
	});


    const options = {
        offerToReceiveAudio: 0,
        offerToReceiveVideo: 1
    };
    pc1.createOffer(options).then(desc => {
        pc1.setLocalDescription(desc)
        pc2.setRemoteDescription(desc)
        pc2.createAnswer(options).then(desc2 => {
            pc2.setLocalDescription(desc2)
            pc1.setRemoteDescription(desc2)
        })
    })
}


function hangup() {
    pc1.close()
    pc2.close()
    pc1 = null
    pc2 = null
}



startBtn.onclick = start
callBtn.onclick = call
hangupBtn.onclick = hangup